﻿using AutoMapper;
using MediatR;
using Medical.Api.Write.Application.Command.PackagingSterilization;
using Medical.Domain.PackagingSterilization;
using Medical.ErrorCode;
using Medical.Interstructrue.Base;

namespace Medical.Api.Write.Application.Handler.PackagingSterilization
{
    /// <summary>
    /// 添加包装注册
    /// </summary>
    public class AddPackagingRegistrationHandler : IRequestHandler<AddPackagingRegistrationCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<PackagingRegistration> packRepository;
        private readonly IMapper mapper;
        private readonly ILogger<AddPackagingRegistrationHandler> logger;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="packRepository"></param>
        /// <param name="mapper"></param>
        /// <param name="logger"></param>
        public AddPackagingRegistrationHandler(IBaseRepository<PackagingRegistration> packRepository, IMapper mapper, ILogger<AddPackagingRegistrationHandler> logger)
        {
            this.packRepository = packRepository;
            this.mapper = mapper;
            this.logger = logger;
        }


        /// <summary>
        /// 添加包装登记实体
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ApiResult<int>> Handle(AddPackagingRegistrationCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();
            int successCount = 0;
            foreach (var packageId in request.EquipmentPackageId)
            {
                var model = new PackagingRegistration
                {
                    Packer = request.Packer,
                    Examiner = request.Examiner,
                    PackingTime = request.PackingTime,
                    EquipmentPackageId = packageId
                };
                var r = packRepository.Create(model);
                if (r > 0)
                {
                    successCount++;
                }
            }
            if (successCount > 0)
            {
                res.Data = successCount;
                res.Code = ApiEnums.Success;
                res.Msg = $"成功添加{successCount}条包装登记记录";
                logger.LogInformation($"成功添加{successCount}条包装登记记录");
                return Task.FromResult(res);
            }
            else
            {
                res.Data = 0;
                res.Code = ApiEnums.Fail;
                res.Msg = "添加包装登记实体失败";
                logger.LogError("添加包装登记实体失败");
                return Task.FromResult(res);
            }
        }
    }
}
